package com.yesjava.springbootjpa.demo.controller;

import com.yesjava.springbootjpa.demo.entity.Category;
import com.yesjava.springbootjpa.demo.entity.Goods;
import com.yesjava.springbootjpa.demo.service.CategoryService;
import com.yesjava.springbootjpa.demo.service.GoodsService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@AllArgsConstructor
public class GoodsController {
    public final GoodsService goodsService;
    public final CategoryService categoryService;


    @RequestMapping("/getgoods")
    @ResponseBody  // 把返回的结果json序列化
    public Object getGoods(@RequestParam(defaultValue = "5") int id, @RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "10") int pageSize) {
        Page<Goods> page = goodsService.findGoodsByCategory(new Category().setId(id), pageNo, pageSize);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "ok");
        map.put("count", page.getTotalElements());
        map.put("data", page.getContent());
        return map;//hello.html..
    }



//    {"name":"天才","price":"66.66","categoryId":7}
    @RequestMapping("/addGoods")
    @ResponseBody  // 把返回的结果json序列化
    public Object addGoods(Integer categoryId,Goods goods) {
        if(categoryId!=null){
            goods.setCategory(new Category().setId(categoryId));//暂时写死成java 类别
        }
        goodsService.saveOrUpdateGoods(goods);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("success", true);
        return map;//hello.html..
    }


    @RequestMapping("/goods_delte")
    @ResponseBody  // 把返回的结果json序列化
    public Object goodsdeltes(@RequestParam("id") List<Integer> id) {

        List<Goods> goodsList = new ArrayList<>();
        for (Integer gid : id) {
            goodsList.add(new Goods().setId(gid));
        }

        goodsService.deleteBatchGoods(goodsList);

        Map<String, Object> map = new HashMap<>();
        map.put("success", true);
        return map;
    }


    @RequestMapping("/getcategorys")
    @ResponseBody  // 把返回的结果json序列化
    public Object getCategorys() {
        List<Category> allTop = categoryService.findAllTop();
        return allTop;//hello.html..
    }
}
